package com.loginlib.table;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loginlib.R;
import com.loginlib.di.component.DaggerTableActivityComponent;
import com.loginlib.di.component.TableActivityComponent;
import com.loginlib.di.module.TableModule;
import com.loginlib.presenters.OpenPresenter;
import com.loginlib.table.adapter.TableAdapter;
import com.wanhe.base.BaseActivity;
import com.wanhe.base.model.base.TableState;
import com.wanhe.base.model.holder.TableInfoHolder;
import com.wanhe.base.util.SPUtils;
import com.wanhe.base.util.ViewUtil;
import com.wanhe.base.websocket.callback.OpenTableCallBack;
import com.wanhe.base.websocket.model.response.BaseResponse;

import java.util.ArrayList;

import javax.inject.Inject;

public class TableNumActivity extends BaseActivity implements View.OnClickListener {

    public static final String TABLE_NAME = "table_name";
    public static final String TABLE_DATA = "table_data";
    public static final String TABLE_BILLAMOUT = "BillAmount";
    public static final String TABLE_UUID = "UUID";

    private GridView gridViewTable;
    private EditText etText;
    private EditText etLineEdit;
    private TextView tvConfim, tvCancle, tvTable, tvVipInfo;

    private int gridNum, edtNum;
    private String phoneNum;
    private String tableID;
    private String uuid;
    private String mobile;
    TableActivityComponent tableActivityComponent;

    @Inject
    OpenPresenter openPresenter;
    String[] items = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
    private TableAdapter adapter;
    //    private VipPresenter vipPresenter;
    private ArrayList<TableState> tableStates;//服务器缓存的会员列表信息

    @Override
    protected void initComponent(Bundle savedInstanceState) {
        setContentView(R.layout.activity_table_num);
        initView();
        initData();
        initInject();
    }

    private void initInject(){
        tableActivityComponent = DaggerTableActivityComponent.builder().tableModule(new TableModule()).build();
        tableActivityComponent.inject(this);
    }
    protected void initEvent() {
        etText.addTextChangedListener(new MaxLengthWatcher(2));
//        cacheVipInfo();
    }


    public class MaxLengthWatcher implements TextWatcher {

        private final int maxLen;

        public MaxLengthWatcher(int maxLen) {
            this.maxLen = maxLen;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int len = s.length();
            if (len > maxLen) {
                int selEndIndex = Selection.getSelectionEnd(s);
                String str = s.toString();
                String newString = str.substring(0, maxLen);
                etText.setText(newString);

                int newLen = etText.getText().length();
                if (selEndIndex > newLen) {
                    selEndIndex = newLen;
                }
                Selection.setSelection(etText.getText(), selEndIndex);
            }
        }
    }


    protected void initData() {
        tableID = getIntent().getStringExtra(TABLE_NAME);
        uuid = getIntent().getStringExtra(TABLE_UUID);
        tvTable.setText("桌" + tableID + "开台");
        tableStates = getIntent().getParcelableArrayListExtra(TABLE_DATA);
//        vipPresenter = new VipPresenter();
//        vipPresenter.setVipViewReference(this);
    }


    public void initView() {
        gridViewTable = (GridView) findViewById(R.id.gv_numbers);
        etText = (EditText) findViewById(R.id.et_people);
        etText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(3)});
        tvConfim = (TextView) findViewById(R.id.tv_Confrim);
        tvCancle = (TextView) findViewById(R.id.tv_Cancle);
        etLineEdit = (EditText) findViewById(R.id.et_lineEdit);
        tvTable = (TextView) findViewById(R.id.tv_table);
        tvVipInfo = (TextView) findViewById(R.id.tv_vipInfo);

        tvConfim.setOnClickListener(this);
        tvCancle.setOnClickListener(this);

        adapter = new TableAdapter(this, items);
        gridViewTable.setAdapter(adapter);
        gridViewTable.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                etText.setText("");
                edtNum = 0;
                gridNum = Integer.valueOf(items[position]);
                adapter.setSelection(position);
                adapter.notifyDataSetChanged();
            }
        });

        etText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s != null && s.length() > 0) {
                    edtNum = Integer.valueOf(s.toString());
                    gridNum = 0;
                }
                adapter.setSelection(-2);
                adapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_Confrim) {//局部设置为全局
            if (gridNum > 0) {
                TableInfoHolder.getInstance().setCustomNum(gridNum);
            } else if (edtNum > 0 && !TextUtils.isEmpty(etText.getText().toString().trim())) {
                TableInfoHolder.getInstance().setCustomNum(edtNum);
            }

            if (TableInfoHolder.getInstance().getCustomNum() > 0) {
                // 2016/8/18 需要等待数据加载成功之后再跳入到主页面
                openPresenter.openTable(uuid, TableInfoHolder.getInstance().getCustomNum(), new OpenTableCallBack() {
                    @Override
                    public void onOpenTable(String body, short source) {
                        Log.d("onOpenTable","onOpenTable");
                        Log.d("onOpenTable","body="+body);
                        Log.d("onOpenTable","source="+source);
                        Gson gson = new Gson();
                        BaseResponse response =   gson.fromJson(body, BaseResponse.class);
                        if(response.getCode()==0){
                            SPUtils.setKeySource(String.valueOf(source));
//                            SPUtils.setBid(new String(bid));
//                            BaseSocketProtocol.bid1 = bid;
                            Intent intent = new Intent();
                            intent.setAction("com.wanhe.meal");
                            startActivity(intent);
                        }else{
                            ViewUtil.ShortToast(TableNumActivity.this,response.getMessage());
                        }
                    }
                });

            } else {
                ViewUtil.ShortToast(this, "亲，请选择人数");
            }

        } else if (i == R.id.tv_Cancle) {
            finish();

        }
    }


}